package br.com.registrofinancas.view;

import org.json.JSONException;
import org.json.JSONObject;

import br.com.registrofinancas.R;
import br.com.registrofinancas.util.AlertSimplesUtils;
import br.com.registrofinancas.util.HttpGetUtils;
import br.com.registrofinancas.util.UsuarioUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
	private EditText etUsuario;
	private EditText etSenha;
	private Button btConfirma;
	private Button btCancela;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		etUsuario = (EditText) findViewById(R.id.activity_login_et_usuario);
		etSenha = (EditText) findViewById(R.id.activity_login_et_senha);
		
		btCancela = (Button) findViewById(R.id.activity_login_bt_cancela);
		btCancela.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});
		
		btConfirma = (Button) findViewById(R.id.activity_login_bt_confirma);
		btConfirma.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				new LoginAsyncTask().execute();
			}
		});		
				
	}
	
	private class LoginAsyncTask extends AsyncTask<Void, Void, String>{
		private ProgressDialog progressDialog;
		
		@Override
		protected String doInBackground(Void... params) {
			String url = HttpGetUtils.getURLLogin(etUsuario.getText().toString(), etSenha.getText().toString());
			String retorno = HttpGetUtils.get( url );
			return retorno;
		}
		
		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setTitle("Aguarde...");
			progressDialog.show();
			return;
		}
		
		@Override
		protected void onProgressUpdate(Void... params) {
			return;
		}		
		
		@Override
		protected void onPostExecute(String valor) {
			progressDialog.dismiss();
			try {
				JSONObject jsonObject = new JSONObject(valor);
				if( (Boolean)jsonObject.get("ok") ){
					Intent menuIntent = new Intent(LoginActivity.this, MenuActivity.class);
					//menuIntent.putExtra("idUsuario", jsonObject.getInt("id"));
					UsuarioUtils.setIdUsuario(jsonObject.getInt("id"));
					startActivity(menuIntent);
					finish();
				}else{
					 AlertSimplesUtils.exibeAlert(LoginActivity.this, "Login", (String)jsonObject.get("texto"));
				}				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return;
		}		
		
		
		
	};
}
